#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash featureCounts-2.0.3.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
if [[ "$buildpath" = "$installpath" ]]; then
    echo "构建路径与安装路径需为不同路径"
    exit 1
fi

set -e
yum install -y wget zlib zlib-devel
wget -t 0 -c -P $buildpath https://nchc.dl.sourceforge.net/project/subread/subread-2.0.3/subread-2.0.3-source.tar.gz
tar -xvf $buildpath/subread-2.0.3-source.tar.gz -C $buildpath && rm -rf $buildpath/subread-2.0.3-source.tar.gz
cd $buildpath/subread-2.0.3-source/src/
sed -i -e 's/CC_EXEC = gcc/CC_EXEC = clang/g' -e 's/-mtune=core2/-mtune=tsv110/g' Makefile.Linux
make featureCounts -f Makefile.Linux
mkdir -p $installpath/subread/bin && cp -p featureCounts $installpath/subread/bin/
mkdir -p $installpath/subread/test/featureCounts && cp -rp ../test/featureCounts/* $installpath/subread/test/featureCounts/

cat>"$installpath/subread/subread_modulefiles"<<EOF
#%Module1.0
conflict subread
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set SUBREAD \$pwd
setenv SUBREAD \$SUBREAD
prepend-path PATH \$SUBREAD/bin
EOF

rm -rf $buildpath/subread-2.0.3-source

